package com.java.wx.controller;

import com.java.bean.Courier;
import com.java.bean.Message;
import com.java.bean.User;
import com.java.mvc.Body;
import com.java.mvc.View;
import com.java.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QRCodeController {

//    @Body("/code/.do")
//    public String (HttpServletRequest req, HttpServletResponse resp) {

    @Body("/code/getCode.do")
    public String getCode(HttpServletRequest req, HttpServletResponse resp) {
        String codeData = (String) req.getSession().getAttribute("codeData");
        if (codeData == null) {
            return new Message(1, getPhone(req)).toJSON();
        }
        return new Message(0, codeData).toJSON();
    }

    @View("/code/personQRCode.do")
    public String personQRCode(HttpServletRequest req, HttpServletResponse resp) {
        String type = req.getParameter("type");
        if ("express".equals(type)) {
            req.getSession().setAttribute("codeData", "express_" + req.getParameter("code"));
        }
        if ("phone".equals(type)) {
            String phone = getPhone(req);
            if (phone == null) {
                return "/log/autoLogin.do";
            }
            req.getSession().setAttribute("codeData", phone);
        }
        return "/personQRCode.html";
    }

    private String getPhone(HttpServletRequest req) {
        String phone;
        User user = UserUtil.getUser(req);
        if (user != null) {
            phone = user.getPhone();
        } else {
            Courier courier = UserUtil.getCourier(req);
            if (courier != null) {
                phone = courier.getPhone();
            } else {
                return null;
            }
        }
        if (phone == null) {
            phone = "msg_用户未绑定手机号码，无法查询快递信息";
        } else {
            phone = "phone_" + phone;
        }
        return phone;
    }


}